/**
 * 所有刷卡功能（会员卡、身份证、医保卡，医保当就诊卡刷）
 */
//注册事件，会员卡按钮id,身份证按钮id，医保卡按钮id，在哪用在哪绑定，也可单独调用其中某个方法
function swipeCardBind(MemberObj, IDid, insuranceid){
	debugger;
	$("#"+MemberObj.Memberid).off("click").on("click",function(){
		readMemberCard(MemberObj.type);    //会员卡(type，区分查询病人信息还是扣费、诊金等类型)
	})
	$("#"+IDid).off("click").on("click",function(){
		readIdentityCard();  //身份证
	})
	$("#"+insuranceid).off("click").on("click",function(){
		MedicalInsuranceCard();   //医保卡，医保卡当就诊卡
	})
	
}
var memberSettingData = {};//参数保存对象
var member_window; //刷卡弹出层
$(document).ready(function()
{
	loadAllCardSetting();

});
/** 初始化参数 */
function loadAllCardSetting() {
    var values = [], views = [];
    views.push("programid||'_'||productid||'_'||paramno as key,value");
    values.push({productid: 1, programid: 116001, paramno: 2}); // 充值打印
    values.push({productid: 1, programid: 116001, paramno: 18});// 是否允许输入卡号
    values.push({productid: 1, programid: 116001, paramno: 14});// 对未入库的卡发卡
    values.push({productid: 1, programid: 116001, paramno: 4}); // 退卡时是否退押金
    values.push({productid: 1, programid: 116001, paramno: 13});// 是否退除工本费
    values.push({productid: 1, programid: 116001, paramno: 12});// 退除工本费的金额
    values.push({productid: 1, programid: 116001, paramno: 17});// 是否必须输入密码
    values.push({productid: 1, programid: 116001, paramno: 16});// 密码长度
    values.push({productid: 1, programid: 116001, paramno: 22});// 禁用基本账户
    values.push({productid: 1, programid: 116001, paramno: 21});// 禁止修改押金
    values.push({productid:1,programid:116001,paramno:72});// 获取读卡器接口地址
    values.push({productid:1,programid:116001,paramno:100});//身份证读卡器接口地址
    values.push({productid:1,programid:116001,paramno:79});//医保卡是否当就诊卡用
    values.push({productid:1,programid:116001,paramno:90});//是否展示输入密码框
    values.push({productid:100,programid:103005,paramno:254});//检索历史就诊记录默认复诊 0不判断复诊  1 判断复诊
    $.ajax({
	    url: memberUrl + '/his/common/query/batchGetSysParamJsonp',
	    data: {
	         'values': JSON.stringify(values),
	         'views': JSON.stringify(views),
	         jsessionids: $.cookie('jsessionids')
	    },
	    type: 'get',
	    cache: false,
	    dataType: 'jsonp',
	    success: function (data) {
	        //数组格式化成对象 如：{"103010_100_37":"2","103010_100_36":"2"}
	        for (var i = 0, len = data.list.length; i < len; i++) {
	            memberSettingData[data.list[i].key] = data.list[i].value;
	        }
	    }
    });
};

/*--------------------------------------------1 会员卡------------------------------------------------------*/
//点击会员卡事件
function readMemberCard(type)
{
	laytplUrl(hosturl + "/tpl/huiyuan_shuaka.html",{}, function(data, html){
		 member_window = layer.open(
			{
				type : 1,
				shade : 0.1,
				area :['560px', '400px'],
				maxmin : false, // 开启最大化最小化按钮
				title : "会员卡信息", // 界面设置
				content : html, // 捕获的元素
				success : function(layero, index)
					{
					debugger;
						setWriteCardNum(type); //是否允许输入卡号
						memberCardChangeEvent(type); //输入框change事件
						$("#please_swing_card").focus();
						$("#remove_shuaka").click(function()
						{
							layer.close(member_window);
						});
						
				}
			});

	});
}

//是否允许输入卡号控制
function setWriteCardNum(type){
	if (memberSettingData['116001_1_18'] == '1')
	{
		$("#shuaka_pronum").hide();
	}
	else
	{
		$("#shuaka_pronum").show();
		$("#shuaka_pronum").on("click", function()
		{
			//输入卡号弹出层
			promptWiteCardNum(type);
		});
	}
}
//输入卡号事件
function promptWiteCardNum(type)
{
	var prompt_index = layer.prompt(
	{
		title : '请输入卡号',
		formType : 0,
		maxlength : 20,
		yes : function(index, layero)
		{
			if ($(".layui-layer-input").val().length <= 20)
			{
				var obj = {};
				obj.pass = $(".layui-layer-input").val();
				obj.type = type;
				obj.layer = prompt_index;
				afterSuccessCardItem(obj);
			}
			else
			{
				layer.alert("最多输入20个字符！",
				{
				icon : 0,
				end : function(index)
				{
					$(".layui-layer-input").focus();
				}
				})
				return;
			}	
		},
		success : function(index, layero)
		{
			$(".layui-layer-input").focus();
		},
		end : function(index, layero)
		{
			$("#please_swing_card").focus();
		}
	});
}

//会员卡接口，获取数据,两种方式，1，不弹出输入卡号窗口，直接读取卡号；2 弹出输入卡号窗口输入卡号
//1，不弹出输入卡号窗口，
var getMemberCardNumToDate = function () {
	var def = $.Deferred();
	debugger;
	if(memberSettingData['116001_1_72']){
		   $.ajax({
		        type: "get",
		        async: true,
		        url:memberSettingData['116001_1_72'],
		        dataType: "jsonp", 
		        processData: false,
		        jsonp:"callback",
				jsonpCallback:"success_jsonpCallback",
		        success: function (cardObj) {
		        	 if(cardObj.result == 'success'){
		        		 def.resolve(cardObj);
		        	 }else{
		        		 layer.msg("读卡失败!",{time:3000,icon:2,skin:'layui-layer-msg2'});
			        	 def.reject();
			        	 return;
		        	 }
		        },
		        error: function (XMLHttpRequest, textStatus, errorThrown) {
		        	layer.alert('请求出现错误,请检查接口地址！',{icon:0});
		        	def.reject();
		        }
		  });;
	   }else{
		   layer.msg("参数没有配置读卡器接口地址！",{icon:0,skin:'layui-layer-msg0'});
		   def.reject();
	   }
	 return def.promise();
}
//2 弹出输入卡号窗口输入卡号
var getMemberCardData = function (cardNumber) {
	cardNumber = cardNumber.toLowerCase();
	var reg = /[^\w\.\/]/ig; 
	if(!cardNumber ||  reg.test(cardNumber)){
		 layer.msg("读取卡号规则不正确,卡号->"+cardNumber+"",{icon:0,skin:'layui-layer-msg0'});
		 return;
	}
    var def = $.Deferred();
	layer.msg('读卡中....', {icon: 16,skin: 'layui-layer-msg16',shade: [0.1, '#393D49'],time:1*500}); 
	var url = memberUrl + "/member/memberManger/queryMemberByNumber";
	var data = 
			{
				cardNumber : cardNumber,
				state : 1,
				jsessionids : $.cookie('jsessionids')
			};
    $.ajax({
    	 url: url,
         dataType: 'jsonp',
         type:'GET',
         data :data,
         success: function (json) {
        	if (json)
			{
				if (json.vcb12 == 2)
				{
					 def.resolve(json);
				}
				else
				{
					//刷卡失败返回改卡的信息
					json.cardNumber = cardNumber;
					showCardFailureMess(json);
					def.reject();
				}
			}
			else
			{
				layer.alert("此卡没有登记，请发卡后在刷卡！",{icon:0});
				def.reject();
				return;
			}
            
        },
        error: function (xhr, textStatus) {
        	 layer.alert("请检查读卡服务是否启动", {icon:0});
             def.reject();
        }
    });
    return def.promise();
};



//读取卡号查询信息
function memberCardChangeEvent(type){
	$("#please_swing_card").on("change", function(){// 请刷卡
		var cardNumber = $(this).val();
		if (cardNumber)
		{
			ajaxGet(memberUrl + "/member/memberManger/queryMemberByNumber",
			{
			cardNumber : cardNumber,
			state : 1,
			jsessionids : $.cookie('jsessionids')
			}, function(json)
			{
				if (json)
				{
					if (json.vcb12 == 2)
					{
						//其他情况直接关闭刷卡弹出层，执行刷卡后业务
						if(type== 1){
							showCardSuccessMess(json);
						}
						else if(type == 6){ //在候诊和接诊病人中查询病人
							getEmitPatient(json);
						}
						layer.close(member_window);
						//刷卡后的业务
						var obj = {};
						obj.cardNumber = cardNumber;
						obj.type = type;
						obj.layer = '';
						afterSuccessCardItem(obj);
					}
					else
					{
						//刷卡失败返回改卡的信息
						json.cardNumber = cardNumber;
						showCardFailureMess(json);
					}
				}
				else
				{
					layer.alert("此卡没有登记，请发卡后在刷卡！",{icon : 0});
					return;
				}
			});
		}
		else
		{
			layer.alert("卡号不能为空！",{icon : 0});
			return;
		}
	});
}
//会员操作 修改密码、充值、退费、退卡操作[没做]

/*--------------------------------------------会员卡end--------------------------------------------------------*/
/*--------------------------------------------2 身份证-----------------------------------------------------*/
//刷卡接口
//var getIdentityCardData = function(){
//  debugger;
//  var def = $.Deferred();
//  layer.msg('读卡中....', {icon: 16,skin: 'layui-layer-msg16',shade: [0.1, '#393D49'],time:1*500});
//  if(memberSettingData['116001_1_100']){
//   $.ajax({
//        type: "get",
//        async: true,
//        url:memberSettingData['116001_1_100'],
//        dataType: "jsonp", 
//        processData: false,
//        jsonp:"callback",
//        jsonpCallback:"success_jsonpCallback",
//        success: function (cardObj) {
//        	 if(cardObj){
//        		 if(cardObj.result == 'sucess' || cardObj.result == 'success'){
//        			
//	        		 
//	        	 }else{
//	        		 layer.msg(cardObj.CardNo,{icon:2,skin:'layui-layer-msg2'});
//        			 $("#ReadCard").attr("disabled",false);
//        			 def.reject();
//        			 return;
//	        	 }
//        	 }else{
//        		 layer.msg('身份证信息数据为空！',{icon:2,skin:'layui-layer-msg2'});
//    			 $("#ReadCard").attr("disabled",false);
//    			 def.reject();
//    			 return;
//        	 }
//        	 if(cardObj.CardNo && cardObj.CardNo.indexOf("请把身份证放在阅读器上") < 0){
//        		 if(cardObj.CardNo && !isNaN(cardObj.CardNo)){
//        			 dataFromIdentityCard(cardObj);
//	        		 ajaxGetJsonp(memberUrl+ "/member/memberManger/queryMemberByNumber",{cardNumber:cardObj.CardNo,state:1},function(json) {
//	     				if (json) {
//	     			  		if(json.vcb12 == 2){
//	     			  			def.resolve(json);
//	     			  		}
//	     				}else{
//	     					layer.alert("无效卡，该卡("+cardObj.CardNo+")没有在系统中登记.",{icon:2});
//	     					def.reject();
//	     				}
//	        		 });	
//	        	 }else{
//	        		 layer.msg("读取卡号为空,请检查读卡器或会员卡！",{icon:0,skin:'layui-layer-msg0'});
//	        		 def.reject();
//	        	 }
//        	 }else{
//        	  layer.msg("读取读取身份证失败,请检查读卡器或身份证是否放在读卡器上！",{icon:0,skin:'layui-layer-msg0'});
//        	  def.reject();
//        	 }
//        },
//        error: function (XMLHttpRequest, textStatus, errorThrown) {
//        	layer.alert('请求出现错误,请检查身份证接口地址！',{icon:0});
//        	def.reject();
//        },
//   	});
//   }else{
//	   layer.msg("参数没有配置身份证读卡器接口地址！",{icon:0,skin:'layui-layer-msg0'});
//	   def.reject();
//   }
//  return def.promise();
//}

function readIdentityCard(issearch){
	debugger;
	layer.msg('读卡中....', {icon: 16,skin: 'layui-layer-msg16',shade: [0.1, '#393D49'],time:1*500});
	if(memberSettingData['116001_1_100']){
		$.ajax({
			type: "get",
			async: true,
			url:memberSettingData['116001_1_100'],
			dataType: "jsonp", 
			processData: false,
			jsonp:"callback",
			jsonpCallback:"success_jsonpCallback",
			success: function (cardObj) {
				if(cardObj){
					if(cardObj.result != 'sucess'){
						layer.msg(cardObj.CardNo,{icon:2,skin:'layui-layer-msg2'});
						$("#ReadCard").attr("disabled",false);
						return;
					}else{
						dataFromIdentityCard(cardObj);
					}
				}else{
					layer.msg('身份证信息数据为空！',{icon:2,skin:'layui-layer-msg2'});
					$("#ReadCard").attr("disabled",false);
					return;
				}
				if(cardObj.CardNo && cardObj.CardNo.indexOf("请把身份证放在阅读器上") < 0){
					if(cardObj.CardNo && !isNaN(cardObj.CardNo)){
						dataFromIdentityCard(cardObj);
						ajaxGetJsonp(memberUrl+ "/member/memberManger/queryMemberByNumber",{cardNumber:cardObj.CardNo,state:1},function(json) {
							if (json) {
								if(json.vcb12 == 2){
									if(memberSettingData['116001_1_17']=="1"){
										pleaseProPwd(json);
									}else{
										if(issearch == 's'){
											getEmitPatient(json);
										}else{
											var obj = {};
											obj.cardNumber = cardObj.CardNo
											searchShuaPromVal(obj);
											queryPatientInfo(json);
											
										}
									}
								}
							}else{
								layer.alert("无效卡，该卡("+cardObj.CardNo+")没有在系统中登记.",{icon:2});
							}
						});	
					}else{
						layer.msg("读取卡号为空,请检查读卡器或会员卡！",{icon:0,skin:'layui-layer-msg0'});
					}
				}else{
					layer.msg("读取读取身份证失败,请检查读卡器或身份证是否放在读卡器上！",{icon:0,skin:'layui-layer-msg0'});
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				layer.alert('请求出现错误,请检查身份证接口地址！',{icon:0});
			},
		});
	}else{
		
		layer.msg("参数没有配置身份证读卡器接口地址！",{icon:0,skin:'layui-layer-msg0'});
	}
}
function pleaseProPwd(json){
    var indexpleaseProPwd=layer.prompt({
        title: '验证会员密码',
        formType: 0,
        maxlength:20,
        success:function(index, layero){
            $(".layui-layer-input").attr('placeholder','请输入密码');
            $(".layui-layer-input").focus();
            $(".layui-layer-input").on('keyup',function(e){
                if(e.keyCode==13){
                    searchPwd(json);
                }
            });
        },yes: function(index, layero){
            searchPwd(json);

        },end:function(index, layero){

        },cancel:function(index, layero){
            $("#error_promptmess").text('请输入会员账号密码');
            $("#please_swing_card").focus();
        },
        btn2:function(index, layero){
            $("#error_promptmess").text('请输入会员账号密码');
            $("#please_swing_card").focus();
        },
    });
}
function searchPwd(json){
    var pass=$(".layui-layer-input").val();
    $.get(rootUrl + "/clidoctor/getMD5PassWord",{password:pass},function(word) {
        if(json.vbu09==word.pass){
//            $(".swing-card-btn button").attr('disabled',false);
            cardMap = json;
            $("#swing_card .swing-card-point").addClass("hidden");
            $("#swing_card .swing-card-info").removeClass("hidden");
//            $("#swing_card .swing-card-btn").removeClass("hidden");
            $("#name").text(json.vaa05);
            $("#cardNum").text(json.vcb04);
            $("#cardIssTime").text(moment(json.vcb16).format("YYYY-MM-DD HH:mm:ss"));
            $("#validTime").text(moment(json.vcb17).format("YYYY-MM-DD"));
            $("#accountNum").text(json.vbu03);
            $("#balance").text(json.vbu14);
            $("#plase_shuaKa").hide();
        }else{
            layer.alert("会员账号密码输入错误！",{icon:2,end:function(index){
                pleaseProPwd(json);
            }})
        }
    });
}
/*--------------------------------------------身份证-end-------------------------------------------------------*/




/*--------------------------------------------3 医保卡------------------------------------------------------*/
//医保卡接口，读取医保数据
var getMedicalInsuranceData = function (params) {
	debugger;
    var def = $.Deferred();
	 layer.msg('读卡中....', {icon: 16,skin: 'layui-layer-msg16',shade: [0.1, '#393D49'],time:1*500}); 
	 clearAllValue();
	 var iaa01_d = $("#iaa01").find("option:eq(1)").val()
	 $("#iaa01").val(iaa01_d).trigger("change");
	 loadiai1();
	 var readCardPar="{\"root\":{\"reginfo\":{\"ie\":\"\"}}}";
	 var iai03;
	 if(!$('#iai01 option:selected').text()){
			iai03=$('#iai01 option:selected').text().substring($('#iai01 option:selected').text().indexOf("(")+1,$('#iai01 option:selected').text().indexOf(")"));
	 }
	 var orderStrUrl = hoinsurance+'/onloadform?id=100210&userId='+$.cookie('loginName')+'&iaa01='+$("#iaa01").val()+'&paramstr=' + readCardPar;  //---接口命令调用方法
//	 var orderStrUrl = "";  //---接口命令调用方法
    $.ajax({
    	 url: orderStrUrl,
         dataType: 'jsonp',
         jsonp: "callback",
         jsonpCallback: "success_jsonpCallback",
        success: function (data) {
            debugger;
            if(data["root"].result=="Success"){
            	 def.resolve(data);
	       	 }else{
	       		 if(data["root"].result=="0"){
	       			 layer.alert("未实现刷卡功能", {icon:0});
	       		 }else{
	       			 layer.alert(data["root"].result, {icon:0});
	       		 }
	       		 def.reject();
	       	 }
        },
        error: function (xhr, textStatus) {
        	 layer.alert("请检查医保服务是否启动", {icon:0});
            def.reject();
        }
    });
    return def.promise();
};
function MedicalInsuranceCard1(){
	debugger;
	 var yibaokaObj;
	 layer.msg('读卡中....', {icon: 16,skin: 'layui-layer-msg16',shade: [0.1, '#393D49'],time:1*500}); 
	 clearAllValue();
	 var iaa01_d = $("#iaa01").find("option:eq(1)").val()
	 $("#iaa01").val(iaa01_d).trigger("change");
	 loadiai1();
	 var readCardPar="{\"root\":{\"reginfo\":{\"ie\":\"\"}}}";
	 var iai03;
	 if(!$('#iai01 option:selected').text()){
			iai03=$('#iai01 option:selected').text().substring($('#iai01 option:selected').text().indexOf("(")+1,$('#iai01 option:selected').text().indexOf(")"));
	 }
	 var orderStrUrl = hoinsurance+'/onloadform?id=100210&userId='+$.cookie('loginName')+'&iaa01='+$("#iaa01").val()+'&paramstr=' + readCardPar;  //---接口命令调用方法
     $.ajax({
    	 url: orderStrUrl,
         dataType: 'jsonp',
         jsonp: "callback",
         jsonpCallback: "success_jsonpCallback",
         success: function (data) {
        	 if(data["root"]){
        		 if(data["root"].result=="Success"){
        			 yibaokaObj = data["root"];
        			 
        			 if(memberSettingData['116001_1_79']==1){
    			    	 if(data["root"]["iar1"]["ie"]["iak05"]){
    			    		//医保卡当就诊卡用,查询病人该医院的信息
	        				 InsuranceAsHospitalCard(data);
    			    	 }
        			 }else{
        				//医保查询人员信息
        				 InsuranceCardValue(data);
        			 }
            	 }else{
            		 if(data["root"].result=="0"){
            			 layer.alert("未实现刷卡功能", {icon:0});
            		 }else{
            			 layer.alert(data["root"].result, {icon:0});
            		 }
            		
            	 }
        	 }
         },
         error: function (xhr) { 
        	 layer.alert("请检查医保服务是否启动", {icon:0});
         }
     });
}




function clearAllValue(){
	$("#saveGuahao").find("input").val("");
	$("#bcb03").val(0).trigger("change");
}
/* 加载医疗类别 与医保机构关联 */
function loadiai1(){
	var iaa01=$("#iaa01").val();
	var url = rootUrl+"/clidoctor/selectDataByScriptId";
	var para = {
			ID:2254,
			paramStr:'{IAA01:'+iaa01+',ACF01=1}'
			};
	$.when($.get(url, para)).done(function(json) {
		if(json.result=="Success"){
			$("#iai01").find("option").remove();
			for (var i = 0; i < json.rows.length; i++) {
				var option = $("<option>").val(json.rows[i].iai01).text(json.rows[i].iai04+"("+json.rows[i].iai03+")");
				$("#iai01").append(option);
			}
			//加载默认值
			$("#iai01").find("option[value='19']").attr("selected",true).trigger("change");
		}
	})
	
}

/*--------------------------------------------医保卡--end------------------------------------------------------*/
/*--------------------------------------------4 医保卡当就诊卡 ----------------------------------------------*/
//医保卡当就诊卡用通过保险卡号搜索病人信息
function InsuranceAsHospitalCard(data){
	var vaa02_i = data["root"]["iar1"]["ie"]["iak05"];
	var param = {
			vaa02:vaa02_i
	}
	$.get(rootUrl + "/clidoctor/selectDataByScriptId",{ID:10000007,paramStr:JSON.stringify(param)}, function(json){
		 if(json.result=="Success"){
			 if(json.list.length > 0){
				   var list = json.list[0];
				   HospitalCardValue(list);
			   }
			 //医保信息赋值，以医保卡查询信息为准包括病人姓名年龄和身份证
			 InsuranceCardValue(data);
		   }
		})
}

/*--------------------------------------------医保卡当就诊卡------------------------------------------------*/

function showCardFailureMess(json){
	var cardNumber = json.cardNumber,vcb12 = json.vcb12;
	var msg;
	switch (vcb12)
	{
		case "0" :
			msg = "无效卡，该卡(" + cardNumber + ")在系统中已建卡.";
			break;
		case "2" :
			msg = "无效卡，该卡(" + cardNumber + ")在系统中已制卡.";
			break;
		case "3" :
			msg = "无效卡，该卡(" + cardNumber + ")在系统中已挂失.";
			break;
		case "4" :
			msg = "无效卡，该卡(" + cardNumber + ")在系统中已注销.";
			break;
		case "5" :
			msg = "无效卡，该卡(" + cardNumber + ")在系统中已作废.";
			break;
		default :
			break;
	}
	if($("#error_promptmess").is(":visiable")){
		$("#error_promptmess").text(msg);
	}else{
		layer.alert(msg,{icon:0});
	}
}